﻿using Common;
using DataBase.Models;
using Orleans;
using Orleans.Concurrency;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Server.Impl
{
    /// <summary>
    /// 地标数据集合，全静态数据
    /// </summary>
    public class MarkerSetImpl : Grain, IMarkerSet
    {
        private   List<MarkerInfo> list = new List<MarkerInfo>();
        private readonly ApplicationDBContext db;

        public MarkerSetImpl(ApplicationDBContext adb)
        {
            db = adb;
        }


        public override async Task OnActivateAsync()
        {
            await base.OnActivateAsync();
            await 重置数据();
        }


        public Task<MarkerInfo?> 获取地标(int x, int y)
        {
            var marker = list.Where(m => Math.Abs(m.X - x) <= 30 && Math.Abs(m.Y - y) <= 30).FirstOrDefault();
            return Task.FromResult(marker);

        }

        public Task<string> 获取对应传输机台(string MarkerID)
        {
            //传输机台的地标编号和入口入地标编号的一一对应关系
            string no = MarkerID + "1";
            return Task.FromResult(no);
        }

        public Task<string> 获取对应地标号(string DeviceID)
        {
            //传输机台的地标编号和入口入地标编号的一一对应关系
            string no = DeviceID[..^1];
            return Task.FromResult(no);
            throw new NotImplementedException();
        }

        public Task 重置数据()
        {
            //从数据库中加载
            var lst = db.markerInfo.ToList();
            var tmp=new List<MarkerInfo>();
            foreach (var m in lst)
            {
                var obj = new MarkerInfo()
                {
                    X = m.X,
                    Y = m.Y,
                    DeviceID = m.DeviceID,
                    Group = m.GroupMarkerID,
                    MarkerID = m.MarkerID,
                    Type = (MarkerEnum)m.Type,
                };
                tmp.Add(obj);
            }
            list = tmp;
            return Task.CompletedTask;
        }


        public Task<MarkerInfo?> 获取指定地标(string MarkerID)
        {
            var marker = list.Find(m => m.MarkerID == MarkerID);
            return Task.FromResult(marker);
        }
    }
     
}
